package com.medical.data.handler;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.medical.data.utils.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        String exceptionMsg = httpServletResponse.getHeader("MyException");
        if(!StringUtils.isEmpty(exceptionMsg)){
            responseServiceException(httpServletResponse, exceptionMsg);
        }
    }
    private void responseServiceException(HttpServletResponse response, String exceptionMsg) {

        AccessDeniedException serviceError = new AccessDeniedException(exceptionMsg);
        Result result = Result.error().message(serviceError.toString());
        JSONObject responseJSONObject = JSON.parseObject(result.toString());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(responseJSONObject.toString());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
